package com.juyu.miliao.authentication.service;

import com.juyu.miliao.authentication.dao.mysql.RegisterAddressDao;
import com.juyu.miliao.authentication.domain.RegisterAddress;
import com.juyu.miliao.common.domain.GaodeConfig;
import com.juyu.miliao.common.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jh
 * 2018/10/7
 */
@Service
@Slf4j
public class RegisterAddressService {

    private final OkHttpClient client = new OkHttpClient();

    @Resource
    private RegisterAddressDao registerAddressDao;

    public void saveByIp(String ip, Long userId) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("key", GaodeConfig.getKey());
        map.put("ip", ip);
        String paramString = OkHttpUtil.combineGetParms(map);
        String url = GaodeConfig.IP_URL + paramString;

        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("根据Ip查询高德失败:ip:{};meg:{}", ip, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    log.error("根据Ip查询高德失败:Unexpected code:{}", response);
                }

                if (response.body() == null) {
                    log.error("根据Ip查询高德:body为空");
                    return;
                }

                String rep = response.body().string();
                if (StringUtils.isEmpty(rep)) {
                    log.error("根据Ip查询高德:返回值rep为空");
                    return;
                }

                JSONObject jsonObject = JSONObject.fromObject(rep);
                String city = "";
                if (jsonObject != null && "1".equals(jsonObject.getString("status"))) {
                    city = jsonObject.getString("city");
                } else {
                    log.error("根据Ip查询高德:rep:{}", jsonObject == null ? "json==null" : jsonObject.toString());
                }

                if (!StringUtils.isEmpty(city)) {
                    //保存
                    RegisterAddress addr = new RegisterAddress();
                    addr.setIp(ip);
                    addr.setUserId(userId);
                    addr.setCity(city);
                    try {
                         int i = registerAddressDao.saveRegisterAddress(addr, userId);
                    } catch (Exception e) {
                        log.error("saveRegisterAddress:{}", e.getMessage());
                    }
                }

            }
        });


    }

}
